package io.rehuo.modules.sms;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import io.rehuo.common.utils.HttpUtil;

import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.ZoneId;

public class Sms {

    private static final String URL = "http://api2.nxcloud.com/api/sms/mtsend";

    private static final String QUERY_URL = "http://api2.nxcloud.com/api/sms/getSmsCdr";

    public static final String SEND_URL = "http://smssh1.253.com/msg/send/json";


    public static void main(String[] args) {
//        alipayAuth();
//        getAccessToken("");
//        sendSms();
        getDetail();
    }

    public static boolean sendSms(String url, String appKey, String secretKey, String phone, String content) {
        String params = "appkey=" + appKey + "&secretkey=" + secretKey + "&phone=" + phone + "&content=" + URLEncoder.encode(content);
        JSONObject jsonObject = HttpUtil.postFormUrlEncoded(url, params);
        String code = jsonObject.getString("code");
        if ("0".equals(code)) {
            return true;
        }
        return false;
    }

    public static boolean sendSmsNew(String url, String appKey, String secretKey, String appId, String phone, String content) {
        HttpRequest request = HttpRequest.post(url);

        //generate md5 key
        final String datetime = String.valueOf(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().getEpochSecond());
        final String sign = SecureUtil.md5(appKey.concat(secretKey).concat(datetime));

        request.header(Header.CONNECTION, "Keep-Alive")
                .header(Header.CONTENT_TYPE, "application/json;charset=UTF-8")
                .header("Sign", sign)
                .header("Timestamp", datetime)
                .header("Api-Key", appKey);


        final String params = JSONUtil.createObj()
                .set("appId", appId)
                .set("numbers", phone)
                .set("content", content)
                .set("senderId", "")
                .toString();

        HttpResponse response = request.body(params).execute();
        if (response.isOk()) {
            String result = response.body();
            JSONObject jsonObject = JSONObject.parseObject(result);
            String status = jsonObject.getString("status");
            System.out.println(jsonObject.toString());
            return status.equals("0");
        }
        return false;
    }

    public static void getDetail() {
        String params = "appkey=wDWhVE3Q&secretkey=MjLmud3S&date=20220915&page_size=10&page=1";
        JSONObject jsonObject = HttpUtil.postFormUrlEncoded(QUERY_URL, params);
        System.out.println(jsonObject);
    }


}